package com.yh.blog.controller;

import com.yh.blog.domain.Blog;
import com.yh.blog.service.BlogService;
import org.apache.ibatis.javassist.NotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

/**
 * 前台首页展示的控制层
 */
@Controller
public class IndexController {
    @Autowired
    private BlogService blogService;

//    跳转到前台页面
    @GetMapping
    public String index(@RequestParam(value = "page",defaultValue = "1") Integer page, Model model, HttpSession session){
        session.removeAttribute("blogTotalNums");
        session.removeAttribute("viewsTotalNums");
        session.removeAttribute("commentsTotalNums");
        session.removeAttribute("messagesTotalNums");
//        由于后台有草稿和发布两种状态我们在前台只显示publish=true的
        Blog condition=new Blog();
        condition.setPublish(true);
//        因为是在共享页面展示的这个所以全部放到session中
        session.setAttribute("blogTotalNums", this.blogService.blogTotalNums());
        session.setAttribute("viewsTotalNums",this.blogService.viewsTotalNums());
        session.setAttribute("commentsTotalNums", this.blogService.commentsTotalNums());
        session.setAttribute("messagesTotalNums", this.blogService.messagesTotalNums());
//        向前台传递分页发布的博客列表和推荐的博客列表
        model.addAttribute("pager",this.blogService.list(condition, page));
        model.addAttribute("RecommendBlog",this.blogService.recommendList());
        return "index";
    }

//      跳转到博客详情页面
    @GetMapping("/blog/{blogId}")
    public String goDetail(@PathVariable("blogId") Integer blogId,Model model) throws NotFoundException {
//        传递经过工具包转换后的博客content的博客
        model.addAttribute("blog",this.blogService.detailWithMark(blogId));
        return "blog_detail";
    }

//      全局查询博客
    @PostMapping("/blog")
    public String search(Model model,String searchText,@RequestParam(value = "page",defaultValue = "1") Integer page){
        model.addAttribute("pager",this.blogService.searchBlog(searchText, page));
        return "search";
    }
}
